package com.clickhouse.sample.jdbc.utils;

import ru.yandex.clickhouse.BalancedClickhouseDataSource;
import ru.yandex.clickhouse.ClickHouseDataSource;
import ru.yandex.clickhouse.settings.ClickHouseProperties;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * ClickHouse工具类(获取单例的数据连接池)
 * [ 使用spring后，此类不需使用 ]
 *
 * @author chenjiacheng
 * @CREATE 2019-06-17 14:05
 */
public class MyClickHouseUtil {

    private MyClickHouseUtil(){}

    private static DataSource dataSource = null;

    private static ClickHouseProperties clickHouseProperties = null;

    /**
     * 需要连接的ClickHouse地址
     */
    //public final static String ADDRESS = "jdbc:clickhouse://172.16.26.242:8121";

    public final static String ADDRESS = "jdbc:clickhouse://119.23.49.70:8121";

    /**
     * 连接的数据库
     */
    private final static String DATABASE = "ck_demo_db";

    /**
     * 登录数据库的用户名
     */
    private final static String USER = "default";

    /**
     * 登录数据库的密码
     */
    private final static String PASSWORD = null;

    // TODO clickhouse集群地址（建议通过搭建nginx tcp集群方式来实现）
    // private final static String ADDRESS = "jdbc:clickhouse://172.16.26.107:8121,172.16.26.107:8122,172.16.26.242:8121,172.16.26.242:8122";

    static {
        clickHouseProperties = new ClickHouseProperties();
        clickHouseProperties.setUser( USER );
        clickHouseProperties.setPassword( PASSWORD );
        clickHouseProperties.setDatabase( DATABASE );
        if( ADDRESS.indexOf(",") > 0 ){
            dataSource = new BalancedClickhouseDataSource( ADDRESS, clickHouseProperties );
        }else{
            dataSource = new ClickHouseDataSource( ADDRESS, clickHouseProperties );
        }

    }

    /**
     * 获取数据库连接池
     * @return  DataSource
     */
    public static DataSource getDataSource(){
        return dataSource;
    }

    /**
     * 从数据库连接池中获取连接
     * @return  Connection
     */
    public static Connection getConnection(){
        if( dataSource == null ){
            throw new RuntimeException(" clickHouseDataSource is null ");
        }
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch ( Exception e ){
            e.printStackTrace();
        }

        if( connection == null ){
            throw new RuntimeException(" clickHouse connection is null ");
        }
        return connection;
    }

}
